package com.bmd.backgroundmanger.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bmd.backgroundmanger.entity.Question;
import com.bmd.backgroundmanger.entity.UserAnswer;
import com.bmd.backgroundmanger.mapper.UserAnswerMapper;
import com.bmd.backgroundmanger.service.IQuestionService;
import com.bmd.backgroundmanger.service.IUserAnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户答题记录Service实现类
 */
@Service
public class UserAnswerServiceImpl extends ServiceImpl<UserAnswerMapper, UserAnswer> implements IUserAnswerService {

    @Autowired
    private IQuestionService questionService;

    @Override
    public boolean submitAnswer(UserAnswer userAnswer) {
        try {
            // 设置提交时间
            userAnswer.setSubmitTime(LocalDateTime.now());
            userAnswer.setCreateTime(LocalDateTime.now());
            
            // 获取题目信息，判断答案是否正确
            Question question = questionService.getById(userAnswer.getQuestionId());
            if (question != null) {
                boolean isCorrect = checkAnswerCorrectness(question, userAnswer.getAnswerContent());
                userAnswer.setIsCorrect(isCorrect);
                
                // 设置得分（简单逻辑：正确得满分，错误得0分）
                if (question.getScore() != null) {
                    userAnswer.setScore(isCorrect ? question.getScore() : 0);
                }
            }
            
            // 保存答题记录
            boolean result = save(userAnswer);
            
            if (result) {
                System.out.println("答题记录保存成功: 用户ID=" + userAnswer.getUserId() + 
                                 ", 题目ID=" + userAnswer.getQuestionId() + 
                                 ", 答案=" + userAnswer.getAnswerContent() + 
                                 ", 正确性=" + userAnswer.getIsCorrect());
            } else {
                System.err.println("答题记录保存失败");
            }
            
            return result;
        } catch (Exception e) {
            System.err.println("提交答案时发生异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 检查答案正确性
     */
    private boolean checkAnswerCorrectness(Question question, String userAnswer) {
        if (question.getCorrectAnswer() == null || userAnswer == null) {
            return false;
        }
        
        String correctAnswer = question.getCorrectAnswer().trim();
        String userAnswerTrimmed = userAnswer.trim();
        
        // 根据题目类型进行不同的判断逻辑
        switch (question.getQuestionType()) {
            case "single":
            case "single_choice":
                // 单选题：直接比较
                return correctAnswer.equalsIgnoreCase(userAnswerTrimmed);
                
            case "multiple":
            case "multiple_choice":
                // 多选题：比较排序后的选项
                return compareMultipleChoice(correctAnswer, userAnswerTrimmed);
                
            case "judge":
            case "true_false":
            case "judgment":
                // 判断题：比较
                return correctAnswer.equalsIgnoreCase(userAnswerTrimmed);
                
            case "essay":
            case "short_answer":
                // 简答题：包含关键词即可（简化处理）
                return userAnswerTrimmed.toLowerCase().contains(correctAnswer.toLowerCase()) ||
                       correctAnswer.toLowerCase().contains(userAnswerTrimmed.toLowerCase());
                
            default:
                // 默认精确匹配
                return correctAnswer.equalsIgnoreCase(userAnswerTrimmed);
        }
    }

    /**
     * 比较多选题答案
     */
    private boolean compareMultipleChoice(String correctAnswer, String userAnswer) {
        String[] correctOptions = correctAnswer.split(",");
        String[] userOptions = userAnswer.split(",");
        
        // 去除空格并排序
        java.util.Arrays.sort(correctOptions);
        java.util.Arrays.sort(userOptions);
        
        for (int i = 0; i < correctOptions.length; i++) {
            correctOptions[i] = correctOptions[i].trim();
        }
        for (int i = 0; i < userOptions.length; i++) {
            userOptions[i] = userOptions[i].trim();
        }
        
        return java.util.Arrays.equals(correctOptions, userOptions);
    }

    @Override
    public List<UserAnswer> getUserAnswerHistory(Integer userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public Double getUserCorrectRate(Integer userId) {
        Integer correctCount = baseMapper.countCorrectAnswersByUserId(userId);
        Integer totalCount = baseMapper.countTotalAnswersByUserId(userId);
        
        if (totalCount == 0) {
            return 0.0;
        }
        
        return (double) correctCount / totalCount * 100;
    }

    @Override
    public Double getQuestionCorrectRate(Integer questionId) {
        List<UserAnswer> answers = baseMapper.selectByQuestionId(questionId);
        if (answers.isEmpty()) {
            return 0.0;
        }
        
        long correctCount = answers.stream()
                .filter(UserAnswer::getIsCorrect)
                .count();
        
        return (double) correctCount / answers.size() * 100;
    }
} 